import SYCM from "~/utils/ali/sycm";
import {brandCustomerCrowd, brandCustomerTrend} from "~/utils/interception/sycm/brandCustomerInterception";
import RequestInterception from "~/utils/RequestInterception";
import Trans from "~/utils/sycm/trans";

export interface SycmBrandAttributePortrait {
    payByrCntIndex: any[],
    payByrCntRate: any[],
    payRateIndex: any[],
    tradeIndex: any[],
    uv: any[],
    customerPrice: any[],
    uvValue: any[],
}

export interface SycmBrand {
    brandId: number;
    canCancel: boolean;
    isMonitored: boolean;
    name: string;
    picUrl: string;
    sourceType: number;
    brandTrend?: SycmBrandTrend | null;
    topTable?: any;
    topShopTable?: any;
    PriceTradeData?: any;
    CateTradeData?: any;
    CustomerTrends?: {
        // 客群指数
        payByrCntIndex: any[];
        // 交易指数
        tradeIndex: any[];
        // 支付转化指数
        payRateIndex: any[];
        // 访客数
        uv: any[];
        // 客单价
        customerPrice: any[];
        // UV价值
        uvValue: any[];
    };
    CustomerPropertyPortrait?: {
        all: SycmBrandAttributePortrait,
        gender: SycmBrandAttributePortrait;
        age: SycmBrandAttributePortrait;
        career: SycmBrandAttributePortrait,
        prov: SycmBrandAttributePortrait,
        city: SycmBrandAttributePortrait,
    },
    PaymentPreference?: {
        pay_cnt: any[],
        price_prefer: any[],
    },
    // 购买偏好
    BuyerPreference?: {
        categoryData: any[],
        brandData: any[],
    }
}

// 品牌指标统计信息
export interface SycmBrandTrend {
    CartHits: any[];
    CltHits: any[];
    FstOnsItmCnt: any[];
    IpvUv: any[];
    PayByrCntIndex: any[];
    PayRateIndex: any[];
    PrePayAmtIndex: any[];
    PrePayItmCnt: any[];
    SeIpvUvHits: any[];
    TradeIndex: any[];
    UserId: any[];
    UvIndex: any[];
    // 访客数
    uv: any[];
    // 客单价
    CustomerPrice: any[];
    // UV价值
    UVValue: any[];
    // 搜索占比
    SeIpvUvHitsRate: any[];
    // 收藏率
    CltHitsRate: any[];
    // 加购率
    CartHitsRate: any[];
    // 收藏加购率
    CltCartHitsRate: any[];
}

export interface SycmBrandLists {
    brand1: SycmBrand | null;
    brand2: SycmBrand | null;
    brand3: SycmBrand | null;
    _data: any,
}

export class SycmBrandMonitor {
    static getMonitorLists() {
        return SYCM.getInternalFiberData('#sycm-mc-ci-brand-monitor > div.oui-card-content', 'memoizedProps.children._owner.memoizedProps.originalTableData.data');
    }

    static async getDates(): Promise<string[]> {
        const data = await SYCM.getInternalFiberData('.oui-pro-composed-chart', 'alternate.memoizedProps.children.props.children.props.data');
        return data.map((item: any) => {
            return item.fullDate;
        });
    }

    // 品牌分析 获取品牌0
    static async getBrands() {
        const data = await SYCM.getInternalFiberData('[id^=__qiankun_microapp_wrapper_for_op_mc] .op-mc-brand-analysis', 'return.memoizedProps');
        const brandLists: SycmBrandLists = {
            brand1: null,
            brand2: null,
            brand3: null,
            _data: data,
        };
        if (typeof data.rivalBrand1 !== 'undefined' && Object.keys(data.rivalBrand1).length > 0) {
            brandLists.brand1 = {
                brandId: data.rivalBrand1.shop.brandId || 0,
                canCancel: data.rivalBrand1.shop.canCancel || false,
                isMonitored: data.rivalBrand1.shop.isMonitored || false,
                name: data.rivalBrand1.shop.name || '',
                picUrl: data.rivalBrand1.shop.picUrl || '',
                sourceType: data.rivalBrand1.shop.sourceType || 0,
            }
        }
        if (typeof data.rivalBrand2 !== 'undefined' && Object.keys(data.rivalBrand2).length > 0) {
            brandLists.brand2 = {
                brandId: data.rivalBrand2.shop.brandId || 0,
                canCancel: data.rivalBrand2.shop.canCancel || false,
                isMonitored: data.rivalBrand2.shop.isMonitored || false,
                name: data.rivalBrand2.shop.name || '',
                picUrl: data.rivalBrand2.shop.picUrl || '',
                sourceType: data.rivalBrand2.shop.sourceType || 0,
            }
        }
        if (typeof data.rivalBrand3 !== 'undefined' && Object.keys(data.rivalBrand3).length > 0) {
            brandLists.brand3 = {
                brandId: data.rivalBrand3.shop.brandId || 0,
                canCancel: data.rivalBrand3.shop.canCancel || false,
                isMonitored: data.rivalBrand3.shop.isMonitored || false,
                name: data.rivalBrand3.shop.name || '',
                picUrl: data.rivalBrand3.shop.picUrl || '',
                sourceType: data.rivalBrand3.shop.sourceType || 0,
            }
        }
        return brandLists;
    }

    // 获取店铺指标统计信息
    static async assignBrandListTrend(brands: SycmBrandLists): Promise<SycmBrandLists> {
        const data = await SYCM.getInternalFiberData('[id^=sycm-mc-ci-brand-analysis-trend] > div.oui-card-content.alife-one-design-sycm-indexes-trend-card-content', 'memoizedProps.children._owner.memoizedProps');
        if (brands.brand1) {
            brands.brand1 = this.assignShopTrend(brands.brand1, 0, data);
        }
        if (brands.brand2) {
            brands.brand2 = this.assignShopTrend(brands.brand2, 1, data);
        }
        if (brands.brand3) {
            brands.brand3 = this.assignShopTrend(brands.brand3, 2, data);
        }
        return brands;
    }

    // 获取店铺指标统计信息
    private static assignShopTrend(brand: SycmBrand, brandType: number, data: any): SycmBrand {
        let keyPrefix = '';
        switch (brandType) {
            case 0:
                keyPrefix = 'rivalBrand1';
                break;
            case 1:
                keyPrefix = 'rivalBrand2';
                break;
            case 2:
                keyPrefix = 'rivalBrand3';
                break;
        }
        brand.brandTrend = {
            CartHits: data.trendData.data[keyPrefix + 'CartHits'],
            CltHits: data.trendData.data[keyPrefix + 'CltHits'],
            FstOnsItmCnt: data.trendData.data[keyPrefix + 'FstOnsItmCnt'],
            IpvUv: data.trendData.data[keyPrefix + 'IpvUv'],
            PayByrCntIndex: data.trendData.data[keyPrefix + 'PayByrCntIndex'],
            PayRateIndex: data.trendData.data[keyPrefix + 'PayRateIndex'],
            PrePayAmtIndex: data.trendData.data[keyPrefix + 'PrePayAmtIndex'],
            PrePayItmCnt: data.trendData.data[keyPrefix + 'PrePayItmCnt'],
            SeIpvUvHits: data.trendData.data[keyPrefix + 'SeIpvUvHits'],
            TradeIndex: data.trendData.data[keyPrefix + 'TradeIndex'],
            UserId: data.trendData.data[keyPrefix + 'UserId'],
            UvIndex: data.trendData.data[keyPrefix + 'UvIndex'],
            uv: data.trendData.data[keyPrefix + 'UvIndex'].map((item: number | string) => {
                if (item === null) {
                    return null;
                }
                if (!item) {
                    return 0;
                }
                return Trans.number(item).toFixed(2);
            }),
            CustomerPrice: data.trendData.data[keyPrefix + 'TradeIndex'].map((item: any, index: number) => {
                if (!data.trendData.data[keyPrefix + 'PayByrCntIndex'][index]) {
                    return 0.00;
                }
                if (item === null) {
                    return null;
                }
                const price = (Trans.number(item) / Trans.number(data.trendData.data[keyPrefix + 'PayByrCntIndex'][index])).toFixed(2);
                if (price === 'NaN') {
                    return '0.00';
                }
                return price;
            }),
            UVValue: data.trendData.data[keyPrefix + 'TradeIndex'].map((item: any, index: number) => {
                if (!data.trendData.data[keyPrefix + 'UvIndex'][index]) {
                    return 0.00;
                }
                if (item === null) {
                    return null;
                }
                const uv = (Trans.number(item) / Trans.number(data.trendData.data[keyPrefix + 'UvIndex'][index])).toFixed(2);
                if (uv === 'NaN') {
                    return '0.00';
                }
                return uv;
            }),
            SeIpvUvHitsRate: data.trendData.data[keyPrefix + 'SeIpvUvHits'].map((item: any, index: number) => {
                if (item === null) {
                    return null;
                } else {
                    if (!data.trendData.data[keyPrefix + 'UvIndex'][index]) {
                        return 0.00;
                    }
                    if (item) {
                        return (Trans.number(item) / Trans.number(data.trendData.data[keyPrefix + 'UvIndex'][index])).toFixed(4);
                    } else {
                        return 0.00;
                    }
                }
            }),
            CltHitsRate: data.trendData.data[keyPrefix + 'CltHits'].map((item: any, index: number) => {
                if (item === null) {
                    return null;
                } else {
                    if (!data.trendData.data[keyPrefix + 'UvIndex'][index]) {
                        return 0.00;
                    }
                    if (item) {
                        return (Trans.number(item) / Trans.number(data.trendData.data[keyPrefix + 'UvIndex'][index])).toFixed(4);
                    } else {
                        return 0.00;
                    }
                }
            }),
            CartHitsRate: data.trendData.data[keyPrefix + 'CartHits'].map((item: any, index: number) => {
                if (item === null) {
                    return null;
                } else {
                    if (!data.trendData.data[keyPrefix + 'UvIndex'][index]) {
                        return 0.00;
                    }
                    if (item) {
                        return (Trans.number(item) / Trans.number(data.trendData.data[keyPrefix + 'UvIndex'][index])).toFixed(4);
                    } else {
                        return 0.00;
                    }
                }
            }),
            CltCartHitsRate: data.trendData.data[keyPrefix + 'CltHits'].map((item: any, index: number) => {
                if (item === null) {
                    return null;
                } else {
                    if (!data.trendData.data[keyPrefix + 'UvIndex'][index]) {
                        return 0.00;
                    }
                    if (item && data.trendData.data[keyPrefix + 'CartHits'][index]) {
                        return (Trans.number(item + data.trendData.data[keyPrefix + 'CartHits'][index]) / Trans.number(data.trendData.data[keyPrefix + 'UvIndex'][index])).toFixed(4);
                    } else {
                        return 0.00;
                    }
                }
            }),
        }
        return brand;
    }

    // 获取品牌的top表格数据
    static async assignBrandListTopTable(brandLists: SycmBrandLists): Promise<SycmBrandLists> {
        const data = brandLists._data;
        if (typeof data['sycm-mc-ci-brand-analysis-top-items-trade-table-rivalBrand1'] === 'undefined' && typeof data['sycm-mc-ci-brand-analysis-top-items-trade-table-rivalBrand2'] === 'undefined') {
            const dom = document.querySelector("#sycm-mc-ci-brand-analysis-top-items div.oui-card-header span.oui-tab-switch > span:nth-child(1)");
            if (dom) {
                (dom as HTMLElement).click();
            }
            return new Promise((resolve, reject) => {
                setTimeout(async () => {
                    resolve(this.assignBrandListTopTable(await this.getBrands()));
                }, 300);
            });
        }
        if (typeof data['sycm-mc-ci-brand-analysis-top-items-flow-table-rivalBrand1'] === 'undefined' && typeof data['sycm-mc-ci-brand-analysis-top-items-flow-table-rivalBrand2'] === 'undefined') {
            const dom = document.querySelector("#sycm-mc-ci-brand-analysis-top-items div.oui-card-header span.oui-tab-switch > span:nth-child(2)");
            if (dom) {
                (dom as HTMLElement).click();
            }
            return new Promise((resolve, reject) => {
                setTimeout(async () => {
                    resolve(this.assignBrandListTopTable(await this.getBrands()));
                }, 300);
            });
        }

        if (brandLists.brand1) {
            brandLists.brand1 = await this.assignBrandTopTable(brandLists.brand1, 0, brandLists._data);
        }
        if (brandLists.brand2) {
            brandLists.brand2 = await this.assignBrandTopTable(brandLists.brand2, 1, brandLists._data);
        }
        if (brandLists.brand3) {
            brandLists.brand3 = await this.assignBrandTopTable(brandLists.brand3, 2, brandLists._data);
        }
        return brandLists;
    }

    private static async assignBrandTopTable(brand: SycmBrand, type: number, data: any): Promise<SycmBrand> {
        let keyPrefix = '';
        switch (type) {
            case 0:
                keyPrefix = 'rivalBrand1';
                break;
            case 1:
                keyPrefix = 'rivalBrand2';
                break;
            case 2:
                keyPrefix = 'rivalBrand3';
                break;
        }
        const d: any[] = [];
        const tradeTableData = data['sycm-mc-ci-brand-analysis-top-items-trade-table-' + keyPrefix].originalTableData.data;
        const flowTableData = data['sycm-mc-ci-brand-analysis-top-items-flow-table-' + keyPrefix].originalTableData.data;
        // console.log(data, tradeTableData, flowTableData);
        // 计算data 将tradeTableData flowTableData合并 根据item.detailUrl 判断是否是同一个商品 如果不存在则直接添加
        tradeTableData.forEach((item: any) => {
            const flowItem = flowTableData.find((flowItem: any) => {
                return flowItem.itemId.value === item.itemId.value;
            });
            if (flowItem) {
                d.push({
                    ...flowItem,
                    ...item,
                });
            } else {
                d.push(item);
            }
        });
        flowTableData.forEach((item: any) => {
            const tradeItem = d.find((tradeItem: any) => {
                return tradeItem.itemId.value === item.itemId.value;
            });
            if (!tradeItem) {
                d.push(item);
            }
        })
        d.forEach((item: any) => {
            // 计算搜索占比
            item.searchRate = 0.00;
            if (typeof item.uvIndex !== 'undefined' && item.uvIndex.value && typeof item.seIpvUvHits !== 'undefined' && item.seIpvUvHits.value) {
                item.searchRate = (Trans.number(item.seIpvUvHits.value) / Trans.number(item.uvIndex.value)).toFixed(4);
            }
            // 计算购买人数
            item.payByrCnt = 0;

            if (typeof item.uvIndex !== 'undefined' && item.uvIndex.value && typeof item.payRateIndex !== 'undefined' && item.payRateIndex.value) {
                item.payByrCnt = (Trans.ratio(item.payRateIndex.value).replaceAll('%', '') / 100 * Trans.number(item.uvIndex.value)).toFixed(0);
            }

            // 计算客单价
            item.customerPrice = 0.00;
            if (item.payByrCnt) {
                item.customerPrice = (Trans.number(item.tradeIndex.value) / item.payByrCnt).toFixed(2);
            }
            // 计算UV价值
            item.uvValue = 0.00;

            if (typeof item.tradeIndex !== 'undefined' && item.tradeIndex.value && typeof item.uvIndex !== 'undefined' && item.uvIndex.value) {
                item.uvValue = (Trans.number(item.tradeIndex.value) / Trans.number(item.uvIndex.value)).toFixed(2);
            }
        })
        brand.topTable = d;
        return brand;
    }

    // 获取品牌的top表格数据
    static async assignBrandListTopShopTable(brandLists: SycmBrandLists): Promise<SycmBrandLists> {
        const data = brandLists._data;
        if (typeof data['sycm-mc-ci-brand-analysis-top-shops-trade-table-rivalBrand1'] === 'undefined' && typeof data['sycm-mc-ci-brand-analysis-top-shops-trade-table-rivalBrand2'] === 'undefined') {
            const dom = document.querySelector("#sycm-mc-ci-brand-analysis-top-shops div.oui-card-header span.oui-tab-switch > span:nth-child(1)");
            if (dom) {
                (dom as HTMLElement).click();
            }
            return new Promise((resolve, reject) => {
                setTimeout(async () => {
                    resolve(this.assignBrandListTopShopTable(await this.getBrands()));
                }, 300);
            });
        }
        if (typeof data['sycm-mc-ci-brand-analysis-top-shops-flow-table-rivalBrand1'] === 'undefined' && typeof data['sycm-mc-ci-brand-analysis-top-shops-flow-table-rivalBrand2'] === 'undefined') {
            const dom = document.querySelector("#sycm-mc-ci-brand-analysis-top-shops div.oui-card-header span.oui-tab-switch > span:nth-child(2)");
            if (dom) {
                (dom as HTMLElement).click();
            }
            return new Promise((resolve, reject) => {
                setTimeout(async () => {
                    resolve(this.assignBrandListTopShopTable(await this.getBrands()));
                }, 300);
            });
        }

        if (brandLists.brand1) {
            brandLists.brand1 = await this.assignBrandTopShopTable(brandLists.brand1, 0, brandLists._data);
        }
        if (brandLists.brand2) {
            brandLists.brand2 = await this.assignBrandTopShopTable(brandLists.brand2, 1, brandLists._data);
        }
        if (brandLists.brand3) {
            brandLists.brand3 = await this.assignBrandTopShopTable(brandLists.brand3, 2, brandLists._data);
        }
        return brandLists;
    }

    private static async assignBrandTopShopTable(brand: SycmBrand, type: number, data: any): Promise<SycmBrand> {
        let keyPrefix = '';
        switch (type) {
            case 0:
                keyPrefix = 'rivalBrand1';
                break;
            case 1:
                keyPrefix = 'rivalBrand2';
                break;
            case 2:
                keyPrefix = 'rivalBrand3';
                break;
        }
        const d: any[] = [];
        const tradeTableData = data['sycm-mc-ci-brand-analysis-top-shops-trade-table-' + keyPrefix].originalTableData.data;
        const flowTableData = data['sycm-mc-ci-brand-analysis-top-shops-flow-table-' + keyPrefix].originalTableData.data;
        // console.log(data, tradeTableData, flowTableData);
        // 计算data 将tradeTableData flowTableData合并 根据item.detailUrl 判断是否是同一个商品 如果不存在则直接添加
        tradeTableData.forEach((item: any) => {
            const flowItem = flowTableData.find((flowItem: any) => {
                return flowItem.sellerId.value === item.sellerId.value;
            });
            if (flowItem) {
                d.push({
                    ...flowItem,
                    ...item,
                });
            } else {
                d.push(item);
            }
        });
        flowTableData.forEach((item: any) => {
            const tradeItem = d.find((tradeItem: any) => {
                return tradeItem.sellerId.value === item.sellerId.value;
            });
            if (!tradeItem) {
                d.push(item);
            }
        })
        d.forEach((item: any) => {
            // 计算搜索占比
            item.searchRate = 0.00;
            if (typeof item.uvIndex !== 'undefined' && item.uvIndex.value && typeof item.seIpvUvHits !== 'undefined' && item.seIpvUvHits.value) {
                item.searchRate = (Trans.number(item.seIpvUvHits.value) / Trans.number(item.uvIndex.value)).toFixed(4);
            }
            // 计算购买人数
            item.payByrCnt = 0;

            if (typeof item.uvIndex !== 'undefined' && item.uvIndex.value && typeof item.payRateIndex !== 'undefined' && item.payRateIndex.value) {
                item.payByrCnt = (Trans.ratio(item.payRateIndex.value).replaceAll('%', '') / 100 * Trans.number(item.uvIndex.value)).toFixed(0);
            }

            // 计算客单价
            item.customerPrice = 0.00;
            if (item.payByrCnt) {
                item.customerPrice = (Trans.number(item.tradeIndex.value) / item.payByrCnt).toFixed(2);
            }
            // 计算UV价值
            item.uvValue = 0.00;

            if (typeof item.tradeIndex !== 'undefined' && item.tradeIndex.value && typeof item.uvIndex !== 'undefined' && item.uvIndex.value) {
                item.uvValue = (Trans.number(item.tradeIndex.value) / Trans.number(item.uvIndex.value)).toFixed(2);
            }
        })
        brand.topShopTable = d;
        // console.log(brand);
        return brand;
    }

    // 注入交易构成 类目交易构成
    static async assignBrandCateTradeData(brands: SycmBrandLists, retry: number = 0): Promise<SycmBrandLists | null> {
        console.log(brands)
        if (retry > 5) {
            return null;
        }
        const data = brands._data;
        if (typeof data['sycm-mc-ci-brand-analysis-trade-cate-table-rivalBrand1'] === 'undefined' || !data['sycm-mc-ci-brand-analysis-trade-cate-table-rivalBrand2']) {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    resolve(this.assignBrandCateTradeData(brands, retry + 1));
                }, 1000);
            });
        }
        // if (typeof data['sycm-mc-ci-brand-analysis-trade-price-rivalBrand1'] === 'undefined' || !data['sycm-mc-ci-brand-analysis-trade-price-rivalBrand2']) {
        //     return new Promise((resolve, reject) => {
        //         setTimeout(() => {
        //             resolve(this.assignBrandCateTradeData(brands,retry + 1));
        //         }, 1000);
        //     });
        // }
        if (brands.brand1) {
            brands.brand1 = await this.assignBrandCateTrade(brands.brand1, 0, data);
        }
        if (brands.brand2) {
            brands.brand2 = await this.assignBrandCateTrade(brands.brand2, 1, data);
        }
        if (brands.brand3) {
            brands.brand3 = await this.assignBrandCateTrade(brands.brand3, 2, data);
        }
        return brands;
    }

    private static async assignBrandCateTrade(brand: SycmBrand, shopType: number, data: any): Promise<SycmBrand> {
        let keyPrefix = '';
        switch (shopType) {
            case 0:
                keyPrefix = 'rivalBrand1';
                break;
            case 1:
                keyPrefix = 'rivalBrand2';
                break;
            case 2:
                keyPrefix = 'rivalBrand3';
                break;
        }
        // console.log(data);
        // 类目构成
        brand.CateTradeData = data['sycm-mc-ci-brand-analysis-trade-cate-table-' + keyPrefix].originalTableData.data;
        // 价格带
        if (typeof data['sycm-mc-ci-brand-analysis-trade-price-' + keyPrefix] !== 'undefined') {
            brand.PriceTradeData = data['sycm-mc-ci-brand-analysis-trade-price-' + keyPrefix].priceData.data;
        }
        return brand;
    }

    // 品牌分析 客群分析 获取品牌
    static async getBrandsByCustomer(): Promise<SycmBrandLists> {
        const data = await SYCM.getInternalFiberData('[id^=__qiankun_microapp_wrapper_for_op_mc] .mc-brandCustomer', 'return.memoizedState');
        const brandLists: SycmBrandLists = {
            brand1: null,
            brand2: null,
            brand3: null,
            _data: await SYCM.getInternalFiberData('[id^=__qiankun_microapp_wrapper_for_op_mc] .mc-brandCustomer', 'return.memoizedProps'),
        };
        if (typeof data.rivalBrand1 !== 'undefined' && Object.keys(data.rivalBrand1).length > 0) {
            brandLists.brand1 = {
                brandId: data.rivalBrand1.value || 0,
                canCancel: false,
                isMonitored: false,
                name: data.rivalBrand1.text || '',
                picUrl: (data.rivalBrand1.img || '').replaceAll('//img.alicdn.com/tps/', '').replaceAll('_48x48.jpg', ''),
                sourceType: 0,
            }
        }
        if (typeof data.rivalBrand2 !== 'undefined' && Object.keys(data.rivalBrand2).length > 0) {
            brandLists.brand2 = {
                brandId: data.rivalBrand2.value || 0,
                canCancel: false,
                isMonitored: false,
                name: data.rivalBrand2.text || '',
                picUrl: (data.rivalBrand2.img || '').replaceAll('//img.alicdn.com/tps/', '').replaceAll('_48x48.jpg', ''),
                sourceType: 0,
            }
        }
        if (typeof data.rivalBrand3 !== 'undefined' && Object.keys(data.rivalBrand3).length > 0) {
            brandLists.brand3 = {
                brandId: data.rivalBrand3.value || 0,
                canCancel: false,
                isMonitored: false,
                name: data.rivalBrand3.text || '',
                picUrl: (data.rivalBrand3.img || '').replaceAll('//img.alicdn.com/tps/', '').replaceAll('_48x48.jpg', ''),
                sourceType: 0,
            }
        }
        return brandLists;
    }

    private static getGetParams(): any {
        const url = window.location.href;
        const query = url.split('?')[1];
        const queryObj = {};
        query.split('&').forEach((item: string) => {
            const [key, value] = item.split('=');
            // @ts-ignore
            queryObj[key] = decodeURIComponent(value);
        });
        return queryObj;
    }

    // 注入客群趋势
    static async assignBrandListCustomerTrend(brands: SycmBrandLists, req: RequestInterception): Promise<SycmBrandLists> {
        const queryObj = this.getGetParams();
        const brandIds = [];
        brandIds.push(queryObj['rivalBrand1Id'] || '');
        brandIds.push(queryObj['rivalBrand2Id'] || '');
        brandIds.push(queryObj['rivalBrand3Id'] || '');
        const data = req.getResponse(brandCustomerTrend, 'json', brandIds.join(',')).data;
        // console.log(data);
        if (brands.brand1) {
            brands.brand1.CustomerTrends = data[brands.brand1.brandId];
            brands.brand1 = this.assignBrandTrendsOtherData(brands.brand1);
        }
        if (brands.brand2) {
            brands.brand2.CustomerTrends = data[brands.brand2.brandId];
            brands.brand2 = this.assignBrandTrendsOtherData(brands.brand2);
        }
        if (brands.brand3) {
            brands.brand3.CustomerTrends = data[brands.brand3.brandId];
            brands.brand3 = this.assignBrandTrendsOtherData(brands.brand3);
        }
        return brands;
    }

    // 注入客群趋势的计算字段
    private static assignBrandTrendsOtherData(brand: SycmBrand): SycmBrand {
        brand.CustomerTrends?.payByrCntIndex.map((item: any, index) => {
            // @ts-ignore
            const brandCustomerTrends = brand.CustomerTrends;
            // @ts-ignore
            if (typeof brandCustomerTrends.uv === 'undefined') {
                // @ts-ignore
                brandCustomerTrends.uv = [];
                // @ts-ignore
                brandCustomerTrends.customerPrice = [];
                // @ts-ignore
                brandCustomerTrends.uvValue = [];
            }
            // 计算访客数
            if (item) {
                // @ts-ignore
                brandCustomerTrends.uv[index] = parseFloat((Trans.number(item) / ((Trans.ratio(brandCustomerTrends.payRateIndex[index]).replaceAll('%', '')) / 100)).toFixed(0));
                // @ts-ignore
                brandCustomerTrends.customerPrice[index] = parseFloat((Trans.number(brandCustomerTrends.tradeIndex[index]) / Trans.number(item)).toFixed(2));
                // @ts-ignore
                brandCustomerTrends.uvValue[index] = parseFloat((Trans.number(brandCustomerTrends?.tradeIndex[index]) / brandCustomerTrends.uv[index]).toFixed(2));
            } else {
                // @ts-ignore
                brandCustomerTrends.uv[index] = 0;
                // @ts-ignore
                brandCustomerTrends.customerPrice[index] = 0;
                // @ts-ignore
                brandCustomerTrends.uvValue[index] = 0;
            }
        });
        return brand;
    }

    static async assignBrandListCustomerPropertyPortrait(brands: SycmBrandLists, req: RequestInterception): Promise<SycmBrandLists> {
        const queryObj = this.getGetParams();
        const brandIds = [];
        brandIds.push(queryObj['rivalBrand1Id'] || '');
        brandIds.push(queryObj['rivalBrand2Id'] || '');
        brandIds.push(queryObj['rivalBrand3Id'] || '');

        if (brands.brand1) {
            brands.brand1 = await this.assignBrandCustomerPropertyPortraitData(brands.brand1, req, queryObj, brandIds);
        }
        if (brands.brand2) {
            brands.brand2 = await this.assignBrandCustomerPropertyPortraitData(brands.brand2, req, queryObj, brandIds);
        }
        if (brands.brand3) {
            brands.brand3 = await this.assignBrandCustomerPropertyPortraitData(brands.brand3, req, queryObj, brandIds);
        }
        return brands;
    }

    private static async assignBrandCustomerPropertyPortraitData(brand: SycmBrand, req: RequestInterception, queryObj: any, brandIds: any[] = []) {
        const getAttrTypeIndexCode = (attrType: string, indexCode: string): Promise<any[]> => {
            let data: any[] = [];
            try {
                data = req.getResponse(brandCustomerCrowd, 'json', ['attrType=' + attrType, 'diffBrandIds=' + brandIds.join(','), 'dateRange=' + queryObj.dateRange, 'cateId=' + queryObj.cateId, 'indexCode=' + indexCode]).data[brand.brandId];
            } catch (e) {
                (document.querySelector('#completeShopPortrait input[value=' + indexCode + ']') as HTMLElement).click();
                return new Promise((resolve, reject) => {
                    setTimeout(async () => resolve(await getAttrTypeIndexCode(attrType, indexCode)), 300);
                });
            }
            return new Promise((resolve, reject) => {
                resolve(data);
            });
        }
        const getAttrTypeData = async (attrType: string): Promise<SycmBrandAttributePortrait> => {
            let payByrCntIndex: any[] = await getAttrTypeIndexCode(attrType, 'payByrCntIndex');
            let payByrCntRate: any[] = await getAttrTypeIndexCode(attrType, 'payByrCntRate');
            let tradeIndex: any[] = await getAttrTypeIndexCode(attrType, 'tradeIndex');
            let payRateIndex: any[] = await getAttrTypeIndexCode(attrType, 'payRateIndex');
            if (attrType === 'all') {
                payByrCntIndex = payByrCntIndex.map((item: any) => {
                    return {
                        ...item,
                        name: '全部',
                    }
                });
                payByrCntRate = payByrCntRate.map((item: any) => {
                    return {
                        ...item,
                        name: '全部',
                    }
                });
                tradeIndex = tradeIndex.map((item: any) => {
                    return {
                        ...item,
                        name: '全部',
                    }
                });
                payRateIndex = payRateIndex.map((item: any) => {
                    return {
                        ...item,
                        name: '全部',
                    }
                });
            } else if (attrType === 'age') {
                const ageMap: any = {
                    '1': '18岁以下',
                    '2': '18-24岁',
                    '3': '25-29岁',
                    '4': '30-34岁',
                    '5': '35-39岁',
                    '6': '40-49岁',
                    '7': '50岁以上',
                };
                payByrCntIndex = payByrCntIndex.map((item: any) => {
                    return {
                        ...item,
                        name: ageMap[item.name] || '未知',
                    }
                });
                payByrCntRate = payByrCntRate.map((item: any) => {
                    return {
                        ...item,
                        name: ageMap[item.name] || '未知',
                    }
                });
                tradeIndex = tradeIndex.map((item: any) => {
                    return {
                        ...item,
                        name: ageMap[item.name] || '未知',
                    }
                });
                payRateIndex = payRateIndex.map((item: any) => {
                    return {
                        ...item,
                        name: ageMap[item.name] || '未知',
                    }
                });
            } else if (attrType === 'gender') {
                const genderMap: any = {
                    '0': '女',
                    '1': '男',
                    '-1': '未知',
                };
                payByrCntIndex = payByrCntIndex.map((item: any) => {
                    return {
                        ...item,
                        name: genderMap[item.name] || '未知',
                    }
                });
                payByrCntRate = payByrCntRate.map((item: any) => {
                    return {
                        ...item,
                        name: genderMap[item.name] || '未知',
                    }
                });
                tradeIndex = tradeIndex.map((item: any) => {
                    return {
                        ...item,
                        name: genderMap[item.name] || '未知',
                    }
                });
                payRateIndex = payRateIndex.map((item: any) => {
                    return {
                        ...item,
                        name: genderMap[item.name] || '未知',
                    }
                });
            }
            return new Promise((resolve, reject) => {
                resolve({
                    payByrCntIndex,
                    payByrCntRate,
                    tradeIndex,
                    payRateIndex,
                    uv: payByrCntIndex.map((item: any, index: number) => {
                        return {
                            name: item.name,
                            value: parseInt(String(Trans.number(item.value) / (Trans.ratio(payRateIndex[index].value).replaceAll('%', '') / 100)))
                        };
                    }),
                    customerPrice: payByrCntIndex.map((item: any, index: number) => {
                        return {
                            name: item.name,
                            value: parseFloat((Trans.number(tradeIndex[index].value) / Trans.number(item.value)).toFixed(2))
                        };
                    }),
                    uvValue: tradeIndex.map((item: any, index: number) => {
                        return {
                            name: item.name,
                            value: parseFloat((Trans.number(item.value) / parseInt(String(Trans.number(payByrCntIndex[index].value) / (Trans.ratio(payRateIndex[index].value).replaceAll('%', '') / 100)))).toFixed(2))
                        };
                    }),
                });
            });
        }
        brand.CustomerPropertyPortrait = {
            all: await getAttrTypeData('all'),
            gender: await getAttrTypeData('gender'),
            age: await getAttrTypeData('age'),
            career: await getAttrTypeData('career'),
            prov: await getAttrTypeData('prov'),
            city: await getAttrTypeData('city'),
        }
        console.log(brand);
        return brand;
    }

    static async assignBrandPaymentPreferenceTable(brands: SycmBrandLists): Promise<SycmBrandLists> {
        const data = brands._data;
        const f = 'sycm-mc-ci-brand-customer--payment-preference';
        if (typeof data[f] !== "undefined") {
            let pay_cntData = data[f].pay_cntData.data;
            let price_preferData = data[f].price_preferData.data;
            if (brands.brand1) {
                brands.brand1.PaymentPreference = {
                    pay_cnt: pay_cntData[brands.brand1.brandId],
                    price_prefer: price_preferData[brands.brand1.brandId],
                }
            }
            if (brands.brand2) {
                brands.brand2.PaymentPreference = {
                    pay_cnt: pay_cntData[brands.brand2.brandId],
                    price_prefer: price_preferData[brands.brand2.brandId],
                }
            }
            if (brands.brand3) {
                brands.brand3.PaymentPreference = {
                    pay_cnt: pay_cntData[brands.brand3.brandId],
                    price_prefer: price_preferData[brands.brand3.brandId],
                }
            }
        }
        return brands;
    }
    static async assignBrandBuyerPreferenceTable(brands: SycmBrandLists): Promise<SycmBrandLists> {
        const data = brands._data;
        const f = 'sycm-mc-ci-brand-customer-purchase-preference';
        if (typeof data[f] !== "undefined") {
            let categoryData = data[f].categoryData.data;
            let brandData = data[f].rbandData.data;
            if (brands.brand1) {
                brands.brand1.BuyerPreference = {
                    categoryData: categoryData[brands.brand1.brandId],
                    brandData: brandData[brands.brand1.brandId],
                }
            }
            if (brands.brand2) {
                brands.brand2.BuyerPreference = {
                    categoryData: categoryData[brands.brand2.brandId],
                    brandData: brandData[brands.brand2.brandId],
                }
            }
            if (brands.brand3) {
                brands.brand3.BuyerPreference = {
                    categoryData: categoryData[brands.brand3.brandId],
                    brandData: brandData[brands.brand3.brandId],
                }
            }
        }
        return brands;
    }
}
